package com.sky.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetmealService;
import com.sky.service.ShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.logging.LogManager;

@RestController
@RequestMapping("/user/shoppingCart")
@Slf4j
@Api("购物车相关接口")
@Transactional
public class ShoppingCartController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 购物车中添加菜品或套餐
     * @return
     */
    @ApiOperation("购物车中添加菜品或套餐")
    @PostMapping("/add")
    public Result add(@RequestBody ShoppingCartDTO shoppingCartDTO){
        //获取用户id
        Long userId= BaseContext.getCurrentId();
        Long setmealId = shoppingCartDTO.getSetmealId();
        ShoppingCart shoppingCart=new ShoppingCart();
        if(setmealId!=null){
            //添加的是套餐
            //判断是否存在购物车中
            LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ShoppingCart::getSetmealId,setmealId);
            ShoppingCart one = shoppingCartService.getOne(lambdaQueryWrapper);
            Setmeal setmeal = setmealService.getById(setmealId);
            if(one!=null){
                one.setNumber(one.getNumber()+1);
                shoppingCartService.updateById(one);
                return Result.success("购物车添加成功");
            }
            //不存在购物车中
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setUserId(userId);
            shoppingCart.setSetmealId(setmealId);
            shoppingCart.setNumber(1);
            shoppingCart.setAmount(setmeal.getPrice());
            shoppingCart.setImage(setmeal.getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            return Result.success("购物车添加成功");
        }
        //添加的是菜品
        //判断是否在购物车中
        Long dishId = shoppingCartDTO.getDishId();
        LambdaQueryWrapper<ShoppingCart> SClambdaQueryWrapper=new LambdaQueryWrapper<>();
        SClambdaQueryWrapper.eq(ShoppingCart::getDishId,dishId);
        ShoppingCart one = shoppingCartService.getOne(SClambdaQueryWrapper);
        //根据DishID查找对应dish
        Dish dish = dishService.getById(dishId);
        if(one!=null){
            //菜品已存在
            one.setNumber(one.getNumber()+1);
            //添加不同口味时要单独考虑
            //TODO 有多种口味时，在购物车上点加号不会出现口味选择，直接将口味相加
            String dishFlavor = shoppingCartDTO.getDishFlavor();
            if(dishFlavor!=null){
                one.setDishFlavor(one.getDishFlavor()+"-"+dishFlavor);
            }
            shoppingCartService.updateById(one);
            return Result.success("购物车添加成功");
        }
        //不存在
        shoppingCart.setName(dish.getName());
        shoppingCart.setUserId(userId);
        shoppingCart.setDishId(dish.getId());
        shoppingCart.setNumber(1);
        shoppingCart.setAmount(dish.getPrice());
        if(shoppingCartDTO.getDishFlavor()!=null){
            shoppingCart.setDishFlavor(shoppingCartDTO.getDishFlavor());
        }
        shoppingCart.setImage(dish.getImage());
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCartService.save(shoppingCart);
        return Result.success("购物车添加成功");
    }

    /**
     * 查看购物车中菜品
     */
    @ApiOperation("查看购物车中菜品")
    @GetMapping("/list")
    public Result<List<ShoppingCart>> getAll(){
        //需要加上用户id作为限制
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(lambdaQueryWrapper);
        return Result.success(list);
    }

    /**
     * 减少菜品或套餐的数量
     */
    @ApiOperation("减少菜品或套餐的数量")
    @PostMapping("/sub")
    public Result<String> sub(@RequestBody ShoppingCartDTO shoppingCartDTO){
        Long dishId = shoppingCartDTO.getDishId();
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        if(dishId!=null){
            //删除的是菜品时
            lambdaQueryWrapper.eq(ShoppingCart::getDishId,dishId);
            lambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
            ShoppingCart SCdish = shoppingCartService.getOne(lambdaQueryWrapper);
            Integer number = SCdish.getNumber();
            if(number==1){
                //数量为1时，直接删除。
                shoppingCartService.remove(lambdaQueryWrapper);
            }else {
                //数量不唯一则直接number-1,对应的口味数据也要进行变化
                SCdish.setNumber(number-1);
                if(SCdish.getDishFlavor()!=null){
                    //TODO 改进
                    String[] flavors = SCdish.getDishFlavor().split("-");
                    String flavor= "";
                    for (int i=0;i<flavors.length-1;i++){
                        flavor=flavor+flavors[i];
                        if(i!=flavors.length-2){
                            flavor=flavor+"-";
                        }
                    }
                    SCdish.setDishFlavor(flavor);
                }
                shoppingCartService.updateById(SCdish);
            }
        }else {
            //删除的是套餐
            Long setmealId =shoppingCartDTO.getSetmealId();
            lambdaQueryWrapper.eq(ShoppingCart::getSetmealId,setmealId);
            ShoppingCart SCsetmeal = shoppingCartService.getOne(lambdaQueryWrapper);
            Integer number = SCsetmeal.getNumber();
            if(number==1){
                shoppingCartService.remove(lambdaQueryWrapper);
            }else {
                SCsetmeal.setNumber(number-1);
                shoppingCartService.updateById(SCsetmeal);
            }
        }
        return Result.success("修改成功");
    }

    /**
     *  清空购物车
     */
    @ApiOperation("清空购物车")
    @DeleteMapping("/clean")
    public Result<String> clean(){
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(lambdaQueryWrapper);
        return Result.success("清空购物车成功");
    }






}
